// pages/screens/propaganda/add/add.js
var util = require('../../../../utils/util.js');
const common = require("../add/common.js");
const jsonData = require("../add/jsondata.js");
var userinfo = wx.getStorageSync('useridentity');
const app = getApp();
const regeneratorRuntime = app.globalData.regeneratorRuntime;
var screencustomerservice = require("../../../../apiservice/screen/screencustomerservice");
var screenpropagandaservice = require("../../../../apiservice/screen/screenpropagandaservice");
var dIndex = 0; //记录上一位患者所选的科室
var mIndex = 0; //记录上一位患者所选的医保类型
var iIndex = 0; //记录上一位患者所选的项目
var preScid; //记录当前上一筛查id
Page({

	/**
	 * 页面的初始数据
	 */
	data: {

		startReservationDate: util.addDateSeg(new Date().getTime(), "Month", 0, '-'),
		endReservationDate: util.addDateSeg(new Date().getTime(), "Month", 2, '-'),
		//来源
		datasource: null,
		//筛查ID
		scid: "",
		//意向客户名字
		leadname: "",
		//意向客户ID
		leadid: '',
		//筛查客户ID
		sccustid: '',
		scinfo: {},
		//是否预约
		isAppoint: false,
		//有无就诊意向
		isIntent: 0,
		//是否跟进
		isTrack: 1,
		//预约时间
		appointmenttothehospitaldate: "",
		//药物数量
		drugQty: "",
		//医院列表
		hospitalList: [],
		//医院索引
		hospitalindex: 0,
		//医院ID
		hospitalid: "",
		//科室列表
		departmentList: [],
		//科室索引
		departmentindex: 0,
		//科室ID
		departmentid: "",
    itemData :[
      { "id": 0, "name": "请选择" },
      { "id": 7, "name": "近视手术" }, 
      { "id": 3, "name": "高度近视" }, 
      { "id": 11, "name": "医学验光配镜" },
      { "id": 2, "name": "儿童眼病" },
      { "id": 8, "name": "斜弱视" },
      { "id": 5, "name": "角膜塑形镜" },
      { "id": 1, "name": "白内障" },
      { "id": 9, "name": "眼底病" },
      { "id": 4, "name": "角膜及眼表" },
      { "id": 10, "name": "眼整形眼眶病" },
      { "id": 12, "name": "青光眼" },
      { "id": 6, "name": "泪道病" },
      { "id": 14, "name": "角膜移植" },
      { "id": 15, "name": "青光VIP特需门诊眼" },
      { "id": 13, "name": "其他" }
    ],
    itemindex: 0,
		//医保地点
		medisuAddr: jsonData.medisuAddr,
		medisuAddrIndex: 0,
		//医保类型
		medisuType: jsonData.medisuType,
		medisuTypeIndex: 0,
		//备注
		remark: "",
		//筛查组长
		ownerid: '',
		//筛查项目
		screenitemid: '',
		buttonText: '提交',
		buttonDisabled: false,
		schooolId: ''
    
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: async function(options) {
		console.log(options);
		//debugger;
		if (options.schoolId) {
			this.setData({
				schoolId: options.schoolId
			})
		}
		this.setData({
			scid: options.scid,
			leadname: options.leadname,
			leadid: options.leadid,
			ownerid: options.ownerid,
			sccustid: options.sccustid,
			screenitemid: options.screenitemid,
			datasource: options.source,
		});
		var resultHos = await this.GetAllHospital();
		var hospitalindex = common.getPickerValue(resultHos, userinfo.siteid);
		var appointmenttothehospitaldate = common.formatTime(new Date(), false);
		this.setData({
			hospitalList: resultHos,
			hospitalindex: hospitalindex,
			appointmenttothehospitaldate: appointmenttothehospitaldate,
			hospitalid: resultHos[hospitalindex].siteId,
		});

		// //宣教 预约赋值
		// new_reservation.new_reservationdate = appointmenttothehospitaldate;
		// new_reservation.new_hospital = resultHos[hospitalindex].siteId;
		// new_reservation.new_lead = options.sccustid;
		// propageanda.new_lead = options.sccustid;

		var departlist = await this.GetDepartment(this.data.hospitalid);
		this.setData({
			departmentList: departlist,
		});
    if (departlist.length>0){
      this.setData({departmentid: departlist[0].new_departmentId});
    }


	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {	
		if(preScid){
			if(preScid!=this.data.scid){
				dIndex = 0;
				mIndex = 0;
        iIndex = 0;
			}else{
				this.setData({
					medisuTypeIndex:mIndex,
					departmentindex:dIndex,
          itemindex:iIndex
				})
			}
		}else{
			preScid = this.data.scid;
		}
		var that = this;
		const eventChannel = this.getOpenerEventChannel();
		eventChannel.on('acceptDataFromOpenerPage', function(data) {
			console.log('scinfo', data.data);
			that.setData({
				scinfo: data.data
			})
		})
    userinfo = wx.getStorageSync('useridentity');
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {

	},
	//有无就诊意向
	onIntentChange: function(e) {
		console.log(e);
		this.setData({
			isIntent: e.detail.index
		});
	},
	//是否跟进
	onTrackChange: function(e) {
		this.setData({
			isTrack: e.detail.index
		});
	},

	//是否预约
	onAppointChange: function(e) {
		if (e.detail.index == 0) {
			this.setData({
				isAppoint: true
			});
			// //宣教赋值
			// propageanda.new_hospital = resultHos[hospitalindex].siteId;
			// propageanda.new_reservationdate = this.data.appointmenttothehospitaldate;
		} else {
			this.setData({
				isAppoint: false
			});
		}
	},
	//预约时间
	changeAppointDate: function(e) {
		this.setData({
			appointmenttothehospitaldate: e.detail.value,
		});
		// //宣教 预约 赋值
		// new_reservation.new_reservationdate=e.detail.value;
		// propageanda.new_reservationdate=e.detail.value;
	},

	//医院
	changeHospital: async function(e) {
		this.setData({
			hospitalindex: e.detail.value,
			hospitalid: this.data.hospitalList[e.detail.value].siteId,
		});
		//  //宣教 预约 赋值
		// new_reservation.new_hospital = this.data.hospitalList[e.detail.value].siteId,
		// propageanda.new_hospital = this.data.hospitalList[e.detail.value].siteId

		var departlist = await this.GetDepartment(this.data.hospitalid);
		if (departlist.length > 0) {
			this.setData({
				departmentList: departlist,
				departmentid: departlist[0].new_departmentId,
				departmentindex: 0
			});
		} else {
			this.setData({
				departmentList: [],
				departmentid: "",
				departmentindex: 0
			});
		}
	},
	//科室
	changeDepartment: function(e) {
		this.setData({
			departmentindex: e.detail.value,
      departmentid: this.data.departmentList[e.detail.value].new_departmentId
		});
		dIndex = e.detail.value
		// new_reservation.new_department=e.currentTarget.id
	},
  //项目
  bindItemChange: function (e) {
    this.setData({
      itemindex: e.detail.value     
    })
    iIndex=e.detail.value
  },
	//医保地点
	changeMedisuAddr: function(e) {
		this.setData({
			medisuAddrIndex: e.detail.value
		});
		//console.log(e);
		// if(e.detail.value!=0)
		// {
		//     new_reservation.new_healthinsuranceplace=e.detail.value
		// }
	},

	//医保类型
	changeMedisuType: function(e) {
		this.setData({
			medisuTypeIndex: e.detail.value,
		});
		mIndex = e.detail.value;
		// new_reservation.new_insurancetype=e.currentTarget.id
	},
	//领用药物数量
	onDrugQtyChange: function(e) {
		this.setData({
			drugQty: e.detail,
		});
		// propageanda.new_countteardrop=e.detail
	},
	//备注
	onRemarkChange: function(e) {
		this.setData({
			remark: e.detail,

		});
		// propageanda.description=e.detail 
		//console.log(e);
	},
	//创建宣讲
	addPropageanda: function() {
		var that = this;
    if (this.data.isAppoint == true) {
      if(this.data.itemindex==0){
        wx.showToast({
          title: '项目不能为空!',
          duration:1500
        })
        return;
      }
    }
		wx.showModal({
			title: '',
			content: '确认提交吗?',
			success(res) {
				if (res.confirm) {
					that.setData({
						//buttonText: '正在提交请稍后。。。',
						buttonDisabled: true
					})
					var obj = {};
					obj.propaganda = that.getPropageanda();
					if (that.data.isAppoint == true) {
						obj.reservation = that.getReservation();
					}
					var customer = {
						new_sc_customerid: that.data.sccustid
					}
					obj.customer = customer;
					obj.lead = that.getLead();
					console.log(obj);
					that.CreatePropagandaAndReservation(obj)
				} else if (res.cancel) {

				}
			}
		})
	},
	//获取宣讲实体
	getPropageanda: function() {
		var propageanda = {};
		propageanda.new_lead = this.data.leadid;
		//就诊意向  无，犹豫均为FALSE
		if (this.data.isIntent == 0) {
			propageanda.new_issee = 1;
		}
		//是否跟进 new_isfollowself 
		propageanda.new_isfollowself = this.data.isTrack;
		if (this.data.isAppoint == true) {
			propageanda.new_isorder = 1;
			propageanda.new_reservationdate = this.data.appointmenttothehospitaldate;
			propageanda.new_hospital = this.data.hospitalid;
			propageanda.new_department = this.data.departmentid;
		}
		propageanda.new_countteardrop = this.data.drugQty;
		if (this.data.medisuAddrIndex != 0) {
			propageanda.new_healthinsuranceplace = this.data.medisuAddrIndex
		}
		if (this.data.medisuTypeIndex != 0) {
			propageanda.new_insurancetype = this.data.medisuTypeIndex
		}
		propageanda.description = this.data.remark;
		propageanda.new_screen = this.data.scid;
		if (this.data.isTrack == 0) {
			propageanda.new_followdoctor = this.data.ownerid;
		}
		propageanda.new_doctor = this.data.ownerid;
		propageanda.ownerid = this.data.ownerid;
		return propageanda
	},
	//获取预约
	getReservation: function() {
		var reservation = {};
		if (this.data.datasource != null) {
			reservation.new_source = this.data.datasource;
		} else {
			reservation.new_source = 3;
		}
		reservation.new_screen = this.data.scid;
		reservation.new_new_screenitem = this.data.screenitemid;
		reservation.new_lead = this.data.leadid;
		if (this.data.medisuTypeIndex != 0) {
			reservation.new_insurancetype = this.data.medisuTypeIndex
		}
		reservation.new_reservationdate = this.data.appointmenttothehospitaldate;
		reservation.new_hospital = this.data.hospitalid;
		reservation.new_department = this.data.departmentid;
    reservation.new_contnt = this.data.itemData[this.data.itemindex].id;
    reservation.new_remark = this.data.remark;
		return reservation
	},

	getLead: function() {
		var lead = {};
		lead.leadid = this.data.leadid;
		if (this.data.medisuTypeIndex != 0) {
			lead.new_insurancetype = this.data.medisuTypeIndex
		}
		if (this.data.medisuAddrIndex != 0) {
			lead.new_insurancelocation = this.data.medisuAddrIndex
		}
		lead.description = this.data.remark;
		lead.lastname = this.data.leadname;
		return lead
	},
	//获取所有医院
	GetAllHospital: async function() {
		var result = await screencustomerservice.GetAllHospital()
		return result.data
	},
	GetDepartment: async function(hospitalId) {
		var result = await screencustomerservice.GetDepartmentByHospitalId(hospitalId);
		return result.data
	},
	//提交宣教
	CreatePropagandaAndReservation: function(obj) {
		var that = this;
		screenpropagandaservice.CreatePropagandaAndReservation(obj).then(function(success) {
			that.showResult(success.data);
			console.log(success);
		}).catch(function(ex) {
			console.log(ex);
			wx.showModal({
				title: '',
				showCancel: false,
				content: '宣教提交失败'
			})
			that.setData({
				buttonDisabled: false
			})

		});
	},
	showResult: function(res) {
		wx.showModal({
			title: '',
			showCancel: false,
			content: '宣教提交完成',
			success: function() {
				wx.navigateBack({
					delta: 1
				})
			}
		})
	},
	toLetter: function() {
		//debugger;
		var scid = this.data.scid;
		var scinfo = this.data.scinfo;
		let toUrl = '../../../print/letter/letter?scid=' + scid
		//debugger;
		if (this.data.schoolId) {
			toUrl += `&schoolId=${this.data.schoolId}`
		}
		wx.navigateTo({
			url: toUrl,
			events: {
				// 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
				acceptDataFromOpenedPage: function(data) {
					console.log(data)
				},
				someEvent: function(data) {
					console.log(data)
				}
			},
			success: function(res) {
				//debugger;
				// 通过eventChannel向被打开页面传送数据
				res.eventChannel.emit('acceptDataFromOpenerPage', {
					data: scinfo
				})
			}
		})
	}
})
